package com.tms.app.tms.ui.base.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.google.gson.Gson;
import com.tms.app.tms.R;
import com.tms.app.tms.bean.NotionBean;
import com.tms.app.tms.bean.UpdateInfo;
import com.tms.app.tms.bean.UserInfo;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.ui.InstallAc;
import com.tms.app.tms.ui.home.MainActivity;
import com.tms.app.tms.ui.login.LoginAt;
import com.tms.app.tms.utils.ApkUpdate;
import com.tms.app.tms.utils.DownloadFileUtil;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.ToolsUtil;
import com.tms.app.tms.widget.MyDialog;
import com.tms.app.tms.widget.MyDialogSelect;
import com.tms.app.tms.widget.CommonDialog;
import com.tms.app.tms.widget.PopuDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;

import java.io.File;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by happy on 2017/8/26.
 */

public class BaseActivity extends AppCompatActivity  implements EasyPermissions.PermissionCallbacks,View.OnClickListener{
    public static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
    public AMapLocationClient mapLocationClient;

    public long mExitTime=0;
    public Gson gson=new Gson();
    private TextView toolbarRightText;
    public MyDialogSelect myDialogSelect;
    public MyDialog loadingDialog;
    private CommonDialog netErrorDialog;
    public String token;
    private TextView toolbarRight2;
    public PopuDialog popuDialog;
    private CommonDialog dialog;
    private CommonDialog commonDialog;
    public Context context;
    private UpdateInfo updateInfo;


    public void clearLocalUserData(){
        SharePreferenceUtil.removeObject(this,UserInfo.class);
        SharePreferenceUtil.remove(this,"token");
        SharePreferenceUtil.remove(this,"mobile");
        SharePreferenceUtil.remove(this,"tzhi");
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState!=null){
            token=SharePreferenceUtil.getToken(this);
        }
        token= SharePreferenceUtil.getToken(this);
        context=this;
    }

    /*个人建议在onResume注册EventBus
           *在可见可交互状态下注册，尽可能少的占用内存
           */
    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        showNotion(new NotionBean());
    }
    /*个人建议在onPause注册EventBus(将当前Activity注册为事件订阅者)
     *不影响功能的情况下提早解除注册，尽可能少的占用内存
     */
    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        hideLoadingDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public <T extends BaseResponse> void  checkResponseBase(T t){
//        ShowMsgUtil.hideLoadingDialog();
//        hideLoading();
        if (t instanceof BaseResponse)
        {
            switch (t.getCode()){
                case 200:
                    break;
                case 404:
                    showNetErrorDialog();
                    break;
                case 3001:
                    showLoadingDialog();
                    break;
                case 3002:
                    showLoadingDialog();
                    break;
                case 4045:
                case 4046:
                case 10012:
                    showMsg("token失效，该账号或在其他机器登陆");
                    Intent intent = new Intent(this, LoginAt.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                case 5001:
                    hideLoadingDialog();
                    break;
                case 6001:
                   // showMsg("请求服务器错误");
                    hideLoadingDialog();
                 //   Snackbar.make()
                    showMsg("请求超时，请检查网络后重试");
                    break;
                case 6002:
                    // showMsg("请求服务器错误");
                    hideLoadingDialog();
                    //   Snackbar.make()
                    //   showMsg("请求超时，请检查网络后重试");
                    break;

            }
        }
    }



    @Override
    protected void onStart() {
        super.onStart();
        requestCodeQRCodePermissions();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    //成功
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        System.out.println("requestCode = [" + requestCode + "], perms = [" + perms + "]");
    }
    //失败
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        System.out.println("requestCode = [" + requestCode + "], perms = [" + perms + "]");
//        for (String perm : perms) {
//            if (perm.equals( android.Manifest.permission.CAMERA)||perm.equals(android.Manifest.permission.READ_EXTERNAL_STORAGE)){
//                Toast.makeText(this,"打开相机或读取文件权限未开启，请开启权限",Toast.LENGTH_SHORT).show();
//                finish();
//            }
//        }
    }
    @AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private void requestCodeQRCodePermissions() {
        String[] perms = {
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.REQUEST_INSTALL_PACKAGES
        };
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "扫描二维码需要打开相机和散光灯的权限", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
        }
    }


    public void showMsg(String msg) {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    public void hideSoftInputFromWindow(Context context, View view){
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }


    public TextView toolbarLeft;
    public TextView toolbarCenter;
    public TextView toolbarRight;

    private  void  initViewToolBar(){
        try {
            toolbarCenter= (TextView) findViewById(R.id.toolbar_center);
            toolbarLeft= (TextView) findViewById(R.id.toolbar_left);
            toolbarRight= (TextView) findViewById(R.id.toolbar_right);
            toolbarRight2= (TextView) findViewById(R.id.toolbar_right_2);
            toolbarRightText= (TextView) findViewById(R.id.toolbar_text_right);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void setToolBarTitle(String title,String strright,int left,int right){
        if (toolbarLeft==null||toolbarRight==null||toolbarCenter==null||toolbarRightText==null)
            initViewToolBar();
        if (toolbarCenter!=null)
            toolbarCenter.setText(title);
        if (toolbarLeft!=null&&left!=-1){
            if (left==0)
                toolbarLeft.setVisibility(View.INVISIBLE);
            else
                toolbarLeft.setBackgroundResource(left);
        }

        if (toolbarRight!=null&&right!=-1){
            if (right==0){
                toolbarRight.setVisibility(View.INVISIBLE);
              //  toolbarRight2.setVisibility(View.INVISIBLE);
            }

            else{
                toolbarRight.setBackgroundResource(right);
            }
        }
        if (strright!=null){
            toolbarRightText.setText(strright);
            toolbarRight.setVisibility(View.GONE);
        }
        toolbarLeft.setOnClickListener(this);
        toolbarRight.setOnClickListener(this);
        toolbarRight2.setOnClickListener(this);
        toolbarRightText.setOnClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void  showNotion(NotionBean notionBean){
            int num=SharePreferenceUtil.getInt(this,"tzhi",0);
            if (num>0){
                try {
                    toolbarRight.getBackground().setLevel(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        else {
                try {
                    toolbarRight.getBackground().setLevel(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    }
    public void setToolBarTitle(String title,int left,int right){
       setToolBarTitle(title,null,left,right);
    }
    public void setToolBarTitle(String title,int left,String right){
        setToolBarTitle(title,right,left,0);
    }


    @Override
    public void onClick(View v) {
        if ((System.currentTimeMillis() - mExitTime) < 2000) {
            mExitTime = System.currentTimeMillis();
            return;
        }
        switch (v.getId())
        {
            case R.id.toolbar_left:
            this.finish();
                break;
            case R.id.toolbar_right:
                popuDialog=new PopuDialog();
                popuDialog.showPopu(this,toolbarRight);
                break;
        }
    }

    public void callPhone(String  phone){
        Intent mIntent = new Intent(Intent.ACTION_CALL);
        mIntent.setData(Uri.parse("tel:"+phone));
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        startActivity(mIntent);
    }

    public void showNetError(){
        showNetError(0);
    }
    public void showNetError(int imglevel){
        showNetError(R.color.colorPrimary,0,"网络异常");
    }
    public void showNetError(int color,int imglevel,String msg){
        try {
             findViewById(R.id.net_errot_layout).setVisibility(View.VISIBLE);
            ImageView imageView= (ImageView) findViewById(R.id.img_net_error);
            TextView textView= (TextView) findViewById(R.id.text_net_error);
            imageView.getBackground().setLevel(imglevel);
            textView.setTextColor(color);
            textView.setText(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hideNerError(){
        try {
            findViewById(R.id.net_errot_layout).setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void showLoadingDialog(){
       showLoadingDialog(" 正在加载请稍候");
    }
    public void showLoadingDialog(String title){
        if (loadingDialog!=null&&loadingDialog.isShowing())
            return;
        loadingDialog= new MyDialog( this,title);
        loadingDialog.show();
    }

    public void hideLoadingDialog(){
        if (loadingDialog!=null)
            loadingDialog.close();
    }

    public void showNetErrorDialog() {
        if (netErrorDialog!=null&&netErrorDialog.isShowing())
            return;
        CommonDialog.getInstance(this,null,2,"网络异常，请检查网络").show();
        netErrorDialog = CommonDialog.getInstance(this,null,2,"网络异常，请检查网络");
        netErrorDialog.show();
    }

    public void hideNetErrorDialog() {
        if (netErrorDialog!=null)
            netErrorDialog.close();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // Do something after user returned from app settings screen, like showing a Toast.
            // 当用户从应用设置界面返回的时候，可以做一些事情，比如弹出一个土司。
//            Toast.makeText(this, R.string.returned_from_app_settings_to_activity, Toast.LENGTH_SHORT)
//                    .show();
        }
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkUpdateInfoStatus(UpdateInfo updateInfo){
        this.updateInfo=updateInfo;
        if (updateInfo.getActiveCode()<0)// 刚刚拿到远程App信息 尚未与本地信息比较
        {
            ApkUpdate.checkUpdateInfoStatus(this,updateInfo);
            return;
        }
        if (updateInfo.getActiveCode()==0){
            showMsg("当前已经是最新版本");
            return;
        }
        if (updateInfo.getActiveCode()==1){// 处于 自主更新区段
            dialog=CommonDialog.getInstance(this,myListener,CommonDialog.btnTwo,"已有最新版本是否下载");
            dialog.show();
            return;
        }
        if (updateInfo.getActiveCode()==2){// 处于 处于提醒区段
            dialog=CommonDialog.getInstance(this,myListener,CommonDialog.btnTwo,"已有最新版本是否下载");
            dialog.show();
            return;
        }
        if (updateInfo.getActiveCode()==3){// 处于强制 更新
          ldd();
            return;
        }
    }

    View.OnClickListener myListener =new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ldd();
        }
    };


    private void ldd(){
        if (updateInfo==null)
            return;
      //  String apkPath = "/sdcard/" + "apk/" + "tms.apk";
        final String apkPath = ToolsUtil.getApkDir() + "tms.apk";
        DownloadFileUtil.downloadFile(updateInfo.getUrl(), apkPath, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {
                    initPdd();
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                if (pd6.getMax()!=total){
                    pd6.setMax((int) total);
                }
                pd6.setProgress((int) current);
//
//                pd6.incrementProgressBy((int)current);
                if(!isDownloading||current>=total){
                    try {

                        pd6.dismiss();

                    } catch (Exception e) {

                    }
                    closeDialog();
                  //  ProgressDialog pd3 = ProgressDialog.show(BaseActivity.this, "提示", "即将安装请稍候", false, true);
                }
            }

            @Override
            public void onSuccess(File result) {
                try {
                    pd6.dismiss();
                } catch (Exception e) {

                }
                closeDialog();
                Intent intent=new Intent(context, InstallAc.class);
                intent.putExtra("apkFile",apkPath);
                context.startActivity(intent);
                 Toast.makeText(context, "下载成功,即将安装", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(context, "下载失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                try {
                    pd6.dismiss();
                } catch (Exception e) {

                }
            }
        });
    }


    private  ProgressDialog pd6;

    private void initPdd(){
        pd6 = new ProgressDialog(this);
        pd6.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        pd6.setCancelable(true);// 设置是否可以通过点击Back键取消
        pd6.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        pd6.setIcon(R.mipmap.ic_launcher);// 设置提示的title的图标，默认是没有的
        pd6.setTitle("正在下载更新请稍候.....");
        pd6.setMax(100);
        /*pd6.setMessage("这是一个水平进度条");*/
        pd6.show();

    }

    public void closeDialog(){
        if (myDialogSelect!=null&&myDialogSelect.isShowing())
            myDialogSelect.close();

        if (loadingDialog!=null&&loadingDialog.isShowing())
            loadingDialog.close();

        if (netErrorDialog!=null&&netErrorDialog.isShowing())
            netErrorDialog.close();

//        if (tokenDialog!=null&&tokenDialog.isShowing())
//            tokenDialog.close();

        if (popuDialog!=null&&popuDialog.isShowing())
            popuDialog.close();

        if (dialog!=null&&dialog.isShowing())
            dialog.close();

        if (commonDialog!=null&&commonDialog.isShowing())
            commonDialog.close();


    }
}